<template>
    <div class="map-tools">
        <!-- 地址搜索 -->
        <el-input v-model="searchAddress" placeholder="地名定位" size="small" class="search-input" clearable
            @keyup.enter="handleSearch"></el-input>
        <el-tooltip content="查询" placement="top">
            <el-button icon="Search" circle @click="handleSearch"></el-button>
        </el-tooltip>

        <!-- 坐标拾取 -->
        <el-tooltip content="坐标拾取" placement="top">
            <el-button icon="LocationInformation" circle @click="toggleCoordinatePick"
                :class="{ active: isPickActive }"></el-button>
        </el-tooltip>

        <!-- 图层管理 -->
        <el-tooltip content="模型管理" placement="top">
            <el-button :icon="LayersIcon" circle @click="LayerClik" />
        </el-tooltip>

        <!-- 测量工具 2025年10月27日10:24:53 先隐藏，点击测量需要拾取，和点击模型查看属性冲突，后面修复-->
        <el-tooltip content="测量工具" placement="top" v-if="false">
            <el-button :icon="ScaleIcon" circle @click="openMeasureTool" :style="{
                backgroundColor: measureTools ? '#1890ff' : '#ffffff',  // 明确颜色值
            }" />
        </el-tooltip>

        <el-tooltip content="缩放到模型" placement="top">
            <el-button :icon="ZoomIcon" circle @click="zoomModel" :style="{
                backgroundColor: measureTools ? '#1890ff' : '#ffffff',  // 明确颜色值
            }" />
        </el-tooltip>

        <!-- 隐藏/显示统计卡片（修改后的核心按钮） -->
        <el-tooltip :content="showStats ? '隐藏统计信息' : '显示统计信息'" placement="top">
            <el-button :icon="showStats ? 'Hide' : 'View'" circle @click="toggleStats" />
        </el-tooltip>

        <el-tooltip :content="showHindHeader ? '隐藏头部信息' : '显示头部信息'" placement="top">
            <el-button :icon="showHindHeader ? 'ArrowUp' : 'ArrowDown'" circle @click="hideHeader" />
        </el-tooltip>

        <!-- 显示子模型 选择框-->
        <el-select v-if="childrenVisible" clearable v-model="selectedModelId" placeholder="请选择子模型"
            @change="handlerChildrenModel" style="width: 240px">
            <el-option v-for="item in childrenList" :key="item.modelId" :label="item.modelName" :value="item.modelId" />
        </el-select>
        <el-tooltip v-if="childrenVisible" :content="childrenVisible1 ? '显示房间信息' : '隐藏房间信息'" placement="top">
            <el-button :icon="childrenVisible1 ? 'View' : 'Hide'" circle @click="hideRoom" />
        </el-tooltip>

        <div v-if="measureTools">
            <el-button class="tool-button" @click="startMeasure('distance')">
                <i>📏</i> 距离测量
            </el-button>
            <el-button class="tool-button" @click="startMeasure('area')">
                <i>🗺️</i> 面积测量
            </el-button>
            <el-button class="tool-button" @click="startMeasure('height')">
                <i>⛰️</i> 高度测量
            </el-button>
            <el-button class="tool-button clear-button" @click="clearMeasure">
                <i>🗑️</i> 清除测量
            </el-button>
            <el-button class="tool-button clear-button" @click="closeMeasureTool">
                <i>🗑️</i> 关闭测量工具
            </el-button>
        </div>

    </div>



    <!-- --------------------------图层管理弹框开始-------------------------------------- -->
    <el-dialog v-model="layersDialog" title="模型管理" :close-on-click-modal="false" :draggable="true"
        :width="isMobile ? '90%' : '900px'" :before-close="handleClose">
        <!-- 卡片容器 -->
        <div class="card-container">
            <el-row :gutter="20">
                <!-- 循环渲染卡片 -->
                <el-col :xs="24" :sm="8" v-for="item in modelDataList" :key="item.modelId">
                    <!-- 卡片组件 - 点击整个卡片切换选中状态 -->
                    <el-card class="content-card" hoverable :class="{ 'selected': selectedId === item.modelId }"
                        @click="selectCard(item.modelId)">

                        <!-- 选中状态标识 -->
                        <div class="selected-indicator" v-if="selectedId === item.modelId">
                            <el-icon>
                                <Check />
                            </el-icon>
                        </div>
                        <!-- 缩略图区域 -->
                        <div class="card-image">
                            <el-image :src="item.modelImgUrl == null ? defaultModeImg : item.modelImgUrl"
                                :alt="item.title" fit="cover" lazy @error="handleImgError(item.modelId)">
                                <template #error>
                                    <div class="image-placeholder">
                                        <el-icon>
                                            <Picture />
                                        </el-icon>
                                    </div>
                                </template>
                            </el-image>
                        </div>
                        <!-- 卡片内容 -->
                        <div class="card-content">
                            <h3 class="card-title">模型名称：{{ item.modelName }}</h3>
                            <el-tooltip effect="dark" popper-style="max-width: 300px;" :content="item.modelDescription"
                                placement="bottom">
                                <p class="card-description">
                                    模型描述：{{ item.modelDescription }}
                                </p>
                            </el-tooltip>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>
        <!-- 底部操作区 -->
        <template #footer>
            <el-button @click="layersDialog = false">取消</el-button>
            <el-button type="primary" @click="confirmSelection" :disabled="!selectedId">
                加载选择模型
            </el-button>
        </template>
    </el-dialog>
    <!-- --------------------------图层管理弹框结束-------------------------------------- -->



</template>

<script setup>
import { ref, inject, onMounted, onUnmounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import * as Cesium from 'cesium';
import ScaleIcon from '@/components/icons/ScaleIcon.vue';
import ZoomIcon from '@/components/icons/Zoom.vue';
import LayersIcon from '@/components/icons/Layers.vue';
import MeasureTool from '@/components/utils/MeasureTool' // 导入测量工具类


// 注入父组件提供的 setShowHeader 方法
// 第一个参数是父组件 provide 的 key，第二个参数是默认值（避免未提供时报错）
const setShowHeader = inject('setShowHeader', () => { });
// 接收Cesium实例和统计卡片显隐状态
const props = defineProps({
    viewer: {
        type: Object,
        required: true
    },
    showStats: {  // 新增：接收父组件的统计卡片显隐状态
        type: Boolean,
        default: true
    },
    onStatsChange: { // 接收父组件的方法
        type: Function,
        required: true // 确保父组件必传，避免调用时报错
    },
    onHindModelChange: { // 接收父组件的方法
        type: Function,
        required: true // 确保父组件必传，避免调用时报错
    },
    modelData: {
        type: Object,
        required: true
    },
    defaultData: {
        type: Object,
        required: true
    }
});
const showHindHeader = ref(false)

// 隐藏 Header：调用注入的方法，传入 false
const hideHeader = () => {
    showHindHeader.value = !showHindHeader.value
    setShowHeader(showHindHeader.value);
};

// 定义事件：向父组件传递统计卡片显隐状态的切换
const emit = defineEmits(['update:showStats']);

const searchAddress = ref('');
const isPickActive = ref(false);

// 切换统计卡片显隐（核心修改）
const toggleStats = () => {
    emit('update:showStats', !props.showStats);  // 通知父组件切换状态
};

// 地址搜索（保持不变）
const handleSearch = async () => {
    const address = searchAddress.value.trim();
    if (!address) {
        ElMessage.warning('请输入地址');
        return;
    }

    const key = '5e5c5b1183d7c9858e0164ef150e8e39'; // 替换为你的密钥
    const url = `https://api.tianditu.gov.cn/geocoder?ds={"keyWord":"${encodeURIComponent(address)}"}&tk=${key}`;

    try {
        const response = await fetch(url);
        const result = await response.json();

        // 解析结果（天地图返回格式）
        if (result.msg === "ok" && result.location) {
            const { lon, lat, score } = result.location;


            if (score < 50) {
                ElMessage.warning('未找到该地址');
                return
            }

            // 定位到搜索结果
            props.viewer.camera.flyTo({
                destination: Cesium.Cartesian3.fromDegrees(Number(lon), Number(lat), 2000), // 高度2000米
                duration: 2 // 飞行时间2秒
            });
        } else {
            ElMessage.warning('未找到该地址');
        }
    } catch (error) {
        ElMessage.error('搜索失败，请检查网络');
    }
};

// 坐标拾取（保持不变）
const toggleCoordinatePick = () => {
    isPickActive.value = !isPickActive.value;
    if (isPickActive.value) {
        props.viewer.screenSpaceEventHandler.setInputAction(event => {
            const cartesian = props.viewer.camera.pickEllipsoid(event.position);
            if (cartesian) {
                const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
                const lng = Cesium.Math.toDegrees(cartographic.longitude).toFixed(6);
                const lat = Cesium.Math.toDegrees(cartographic.latitude).toFixed(6);
                ElMessage.success(`坐标：经度 ${lng}，纬度 ${lat}`);
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    } else {
        props.viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }
};
//-----------------------------------------------------图层控制弹框开始-----------------------------------
const modelDataList = ref([])
const layersDialog = ref(false)
// 当前选中的卡片ID（单选核心）
const selectedId = ref(null);
// 是否为移动设备（响应式判断）
const isMobile = ref(false);
const selectedModelId = ref('');
const defaultModeImg = ref(new URL('@/assets/model/model.png', import.meta.url).href)




//点击图层管理
const LayerClik = () => {
    layersDialog.value = true
}

// 选择卡片（单选逻辑）
const selectCard = (id) => {
    if (id) {
        selectedId.value = id;
    } else {
        selectedId.value = null
    }
};
const childrenVisible = ref(false)
const childrenVisible1 = ref(false)
const childrenList = ref([])
//记录选中的房间模型，用于显示隐藏房间信息
const handlerChildrenModelItem = ref(null)


// 确认选择
const confirmSelection = () => {
    if (!selectedId.value) return;

    // 获取选中的完整数据
    const selectedItem = modelDataList.value.find(item => item.modelId === selectedId.value);

    // 这里可以添加业务逻辑，如提交选中数据
    layersDialog.value = false;
    // 重置选中状态（根据需求决定是否保留）
    selectedId.value = selectedItem.modelId;

    //调用上层选中显示
    props.onStatsChange(selectedItem);

    //切换默认隐藏多面体房间信息
    childrenVisible1.value = false
    props.onHindModelChange(null, false);

    let target = true
    if (selectedItem.modelFilePath.includes("bim")) {
        target = false
    }

    if (selectedItem.childrenList.length > 0) {
        childrenVisible.value = true
        childrenList.value = selectedItem.childrenList.sort((a, b) => a.modelId - b.modelId);
        // emit('update:showStats', target);  // 通知父组件切换状态
    } else {
        childrenVisible.value = false
        childrenList.value = []
    }
};

const handlerChildrenModel = (modelId) => {
    //切换默认隐藏多面体房间信息
    childrenVisible1.value = false
    props.onHindModelChange(null, false);

    if (modelId) {
        let item = childrenList.value.find(item => item.modelId === modelId);
        handlerChildrenModelItem.value = item
        //调用上层选中显示
        props.onStatsChange(item);
    } else {
        props.onStatsChange(null);
        handlerChildrenModelItem.value = null;
    }
}


// 处理弹框关闭
const handleClose = (done) => {
    // 关闭时重置选中状态
    done();
};

// 处理图片加载错误
const handleImgError = (modelId) => {
    // 直接修改响应式数据
    const index = modelDataList.value.findIndex(item => item.modelId === modelId)
    if (index !== -1) {
        // 使用 Vue 的响应式更新
        modelDataList.value[index].modelImgUrl = defaultModeImg.value

        // 强制触发更新（如果需要）
        // modelDataList.value = [...modelDataList.value]
    }

};

// 响应式处理
const checkIsMobile = () => {
    isMobile.value = window.innerWidth < 768;
};

watch(() => props.modelData, (newModelData) => {
    if (newModelData) {
        modelDataList.value = [...newModelData]
        const targetIndex = modelDataList.value.findIndex(item => item.modelIsDefault === true);
        if (targetIndex > -1) {
            selectedId.value = modelDataList.value[targetIndex].modelId
        }
    }
})
watch(() => props.defaultData, (newModelData) => {
    if (newModelData) {
        if (newModelData.length > 0) {
            childrenVisible.value = true
            childrenList.value = newModelData.sort((a, b) => a.modelId - b.modelId);
        } else {
            childrenVisible.value = false
            childrenList.value = []
        }

    }
})

//-----------------------------------------------------图层控制弹框结束-----------------------------------


//测量工具

let measureTool = null

const measureTools = ref(false)
// 测量工具（保持不变）
const openMeasureTool = () => {
    measureTools.value = !measureTools.value
};
const closeMeasureTool = () => {
    measureTools.value = false
};
//测量
const startMeasure = (type) => {
    try {
        switch (type) {
            case 'distance':
                measureTool.setupDistanceMeasurement();
                break;
            case 'area':
                measureTool.measureArea();
                break;
            case 'height':
                measureTool.measureHeight();
                break;
        }
    } catch (err) {
        console.log("测量工具异常", err)
    }

}
//清除测量
const clearMeasure = () => {
    measureTool.clear()
};

//-----------------缩放到图层
const zoomModel = () => {
    //调用上层选中显示
    props.onStatsChange(-1);
}

onMounted(() => {
    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);
    // 初始化测量工具
    measureTool = new MeasureTool(props.viewer)
});

onUnmounted(() => {
    window.removeEventListener('resize', checkIsMobile);
});

//显示隐藏房间信息
const hideRoom = () => {
    childrenVisible1.value = !childrenVisible1.value
    props.onHindModelChange(handlerChildrenModelItem.value, childrenVisible1.value);
}
</script>

<style scoped>
/* 核心修改：调整定位到上面左边 */
.map-tools {
    position: absolute;
    top: 10px;
    left: 20px;
    /* 距离左边20px */
    /* 移除居中对齐：删除 transform: translateX(-50%) */
    display: flex;
    align-items: center;
    gap: 10px;
    /* 按钮间距 */
    padding: 8px 12px;
    /* 稍微缩减内边距，更紧凑 */
    background: #ffffff;
    border-radius: 8px;
    z-index: 20;
    height: 40px;
    /* 确保在地图和统计卡片上方 */
    box-shadow: 0 2px 10px rgba(209, 4, 4, 0.1);
}

/* 搜索框宽度可适当缩减，适应左边布局 */
.search-input {
    width: 200px;
}

.el-button.active {
    background-color: #1890ff;
    color: white;
}

.card-container {
    max-height: 60vh;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 10px 0;
}

/* 卡片基础样式 */
.content-card {
    height: 100%;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
    border: 2px solid transparent;
}

/* 卡片悬停效果 */
.content-card:not(.selected):hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
    border-color: #e0e0e0;
}

/* 选中状态样式 */
.content-card.selected {
    border-color: var(--el-color-primary);
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 选中标识 */
.selected-indicator {
    position: absolute;
    top: 12px;
    right: 12px;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background-color: var(--el-color-primary);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 图片区域 */
.card-image {
    width: 100%;
    height: 200px;
    overflow: hidden;
}

.card-image :v-deep(.el-image) {
    width: 100%;
    height: 100%;
    transition: transform 0.5s ease;
}

.content-card:hover .card-image :v-deep(.el-image) {
    transform: scale(1.05);
}

.image-placeholder {
    width: 100%;
    height: 100%;
    background-color: #f5f5f5;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #909399;
}

/* 卡片内容 */
.card-content {
    padding: 16px;
    text-align: left;
}

.card-title {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
    margin-bottom: 8px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.card-description {
    font-size: 13px;
    color: #606266;
    line-height: 1.5;
    margin-bottom: 12px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
}



.card-meta {
    display: flex;
    align-items: center;
}

.meta-type {
    font-size: 12px;
    color: var(--el-color-primary);
    background-color: rgba(64, 158, 255, 0.1);
    padding: 2px 8px;
    border-radius: 4px;
}


:v-deep(.el-select-dropdown) {
    max-height: 500px;
}
</style>